import { EventEmitter } from 'events';
import { curry, is } from "ramda"
const Task = require('data.task')

class Emitter extends EventEmitter { }
const emitter = new Emitter();
emitter.setMaxListeners(100);

// publish :: eventName -> data -> Task err null
export const publish = curry((eventName: string, data) =>
    new Task((rej, res) => res(emitter.emit(eventName, data))) // pass an array to data if multiple parameters required in func
)

export const subscribe = curry((eventName: string, func: any) => {
    emitter.on(eventName, data => {
        if (!is(Array, data)) data = [data];
        const result = func(...data);
        if (result instanceof Task) {
            result.fork(
                err => { console.log(`Error occur in publish [ ${eventName} ]: `, err); },
                () => { }
            ); // consider: app.emit('error', error);
        }
    })
})